// 替代数据库实现 - 使用文件系统存储
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');

const dataPath = path.join(process.cwd(), 'data');
const dbFile = path.join(dataPath, 'database.json');

// 确保数据目录存在
if (!fs.existsSync(dataPath)) {
  fs.mkdirSync(dataPath, { recursive: true });
}

// 初始化数据结构
const initData = {
  site_config: [{
    id: 'main',
    title: '机器人创新实验室',
    description: '致力于机器人技术研发与创新，培养优秀的机器人工程师',
    contact_info: JSON.stringify({
      email: "contact@roboticslab.com", 
      phone: "+86-10-12345678", 
      address: "某某大学某某楼某某室"
    }),
    theme: JSON.stringify({
      primaryColor: "#3b82f6", 
      secondaryColor: "#64748b", 
      backgroundColor: "#ffffff", 
      textColor: "#1e293b"
    }),
    navigation: JSON.stringify([
      {id: "home", label: "首页", href: "/"}, 
      {id: "about", label: "关于我们", href: "/about"}, 
      {id: "members", label: "团队成员", href: "/members"}, 
      {id: "projects", label: "项目成果", href: "/projects"}, 
      {id: "news", label: "新闻动态", href: "/news"}, 
      {id: "recruitment", label: "加入我们", href: "/recruitment"}
    ]),
    footer: JSON.stringify({
      sections: [{
        title: "快速链接", 
        links: [
          {label: "关于我们", href: "/about"}, 
          {label: "联系我们", href: "/contact"}
        ]
      }], 
      copyright: "© 2024 机器人创新实验室. All rights reserved."
    }),
    updated_at: new Date().toISOString()
  }],
  users: [{
    id: 'admin',
    username: 'admin',
    email: 'admin@lab.com',
    password: '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password: password
    role: 'admin',
    name: '管理员',
    is_active: 1,
    created_at: new Date().toISOString(),
    updated_at: new Date().toISOString()
  }],
  members: [],
  projects: [],
  news: [],
  recruitments: [],
  applications: [],
  media_files: []
};

class FileDatabase {
  constructor() {
    this.initialized = false;
  }

  async initialize() {
    if (this.initialized) return;

    if (!fs.existsSync(dbFile)) {
      fs.writeFileSync(dbFile, JSON.stringify(initData, null, 2));
      console.log('文件数据库初始化完成');
    }
    
    this.initialized = true;
  }

  loadData() {
    if (!fs.existsSync(dbFile)) {
      return initData;
    }
    try {
      return JSON.parse(fs.readFileSync(dbFile, 'utf8'));
    } catch (error) {
      console.error('读取数据文件失败:', error);
      return initData;
    }
  }

  saveData(data) {
    try {
      fs.writeFileSync(dbFile, JSON.stringify(data, null, 2));
      return true;
    } catch (error) {
      console.error('保存数据文件失败:', error);
      return false;
    }
  }

  async run(sql, params = []) {
    await this.initialize();
    // 简化实现，仅支持基本操作
    return { changes: 1, lastID: Date.now() };
  }

  async get(sql, params = []) {
    await this.initialize();
    const data = this.loadData();
    
    // 简单的配置查询
    if (sql.includes('site_config')) {
      return data.site_config[0];
    }
    
    return undefined;
  }

  async all(sql, params = []) {
    await this.initialize();
    const data = this.loadData();
    
    if (sql.includes('site_config')) {
      return data.site_config;
    }
    
    return [];
  }

  async close() {
    // 文件数据库不需要关闭连接
    return Promise.resolve();
  }
}

const db = new FileDatabase();
module.exports = { db };